#include "licence.h"
#include<QString>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/if_ether.h>
#include <net/if.h>
#include <stdio.h>

#ifdef Q_OS_LINUX
#include <linux/sockios.h>
#endif

licence::licence()
{
}


bool licence::getLicence(QString &devID, LICENCE &licence)
{
    return this->idToLicence(devID, licence);
}

bool licence::decryptLicence(char* license, char* devID)
{
    return this->licenceToId(license, devID);

//    qDebug() << "licnce........." <<

}

bool licence::checkLicence(QString &msg)
{
    //检查licese是否正确
    DEVICEIDLIST list;
    get_mac(list);
    QString hardCode = list.at(0);

    char license[64];
    char key[64];

    int chownReturn;
    int chmodReturn;

    QString licensepath = g_installPath + "/license/license";
    QFile file(licensepath);

    bool licenseIsRight = false;
//    QString msg;

    if (!file.exists())
    {
        msg = QObject::tr("license出错,未检测到license文件");

        QMessageBox msgBox;
        msgBox.setText(QString::fromLocal8Bit(msg.toLatin1()));
        QPushButton *saveButton = msgBox.addButton(msg, QMessageBox::ActionRole);
        QPushButton *cancelButton = msgBox.addButton(msg, QMessageBox::ActionRole);

        QString nameStr = QObject::tr("选择license文件");
        saveButton->setText(QString::fromLocal8Bit(nameStr.toLatin1()));

        nameStr = QObject::tr("取消");
        cancelButton->setText(QString::fromLocal8Bit(nameStr.toLatin1()));

        msgBox.exec();


        if(msgBox.clickedButton() == saveButton)
        {
            QString licensePath = QFileDialog::getOpenFileName((QWidget *)&msgBox, QObject::tr("Choose license"),
                                                               "./", QObject::tr("ALL FILE(*)"));
            QFile file;
            QString appLicensePath = g_installPath + "/license/license";

            QString licnsePath = g_installPath + "/license/";
            QDir liceseDir(licnsePath);
            if (!liceseDir.exists())
            {
                liceseDir.mkdir(licnsePath);
            }

            file.remove(appLicensePath);
            file.copy(licensePath, appLicensePath);

#ifdef Q_OS_LINUX
            __uid_t uid = getuid();
            __gid_t gid = getgid();
            chownReturn = chown(appLicensePath.toLatin1().data(), uid, gid);
            chmodReturn = chmod(appLicensePath.toLatin1().data(), 0777);
#endif
            QString msg;
            licenseIsRight = this->checkLicence(msg);
        } else {
            return licenseIsRight;
        }

    } else {
        file.open(QIODevice::ReadWrite);
        QDataStream out(&file);
        QByteArray bytes;
        out >> bytes;
        strcpy(license, bytes);
        decryptLicence(license, key);

        QString strKey = key;
//        qDebug() << "hardCode:" << hardCode << "key---->>" << strKey << "license:" << license;
        if (hardCode == strKey)
        {
            licenseIsRight = true;
        } else {
//            qDebug() << "fail mac0000000000000000";

            msg = QObject::tr("license出错,请检查是否安装了正确的license");
            QMessageBox msgBox;
            msgBox.setText(QString::fromLocal8Bit(msg.toLatin1()));
            QPushButton *saveButton = msgBox.addButton(msg, QMessageBox::ActionRole);

            QPushButton *cancelButton = msgBox.addButton(msg, QMessageBox::ActionRole);

            QString nameStr = QObject::tr("选择license文件");
            saveButton->setText(QString::fromLocal8Bit(nameStr.toLatin1()));

            nameStr = QObject::tr("取消");
            cancelButton->setText(QString::fromLocal8Bit(nameStr.toLatin1()));

            msgBox.exec();

            if(msgBox.clickedButton() == saveButton)
            {
                QString licensePath = QFileDialog::getOpenFileName((QWidget *)&msgBox, QObject::tr("Choose license"),
                                                                   "./", QObject::tr("ALL FILE(*)"));

                QFile file;
                QString appLicensePath = g_installPath + "/license/license";
                file.remove(appLicensePath);
                file.copy(licensePath, appLicensePath);

#ifdef Q_OS_LINUX
                __uid_t uid = getuid();
                __gid_t gid = getgid();
                chownReturn = chown(appLicensePath.toLatin1().data(), uid, gid);
                chmodReturn = chmod(appLicensePath.toLatin1().data(), 0777);
#endif
                QString msg;
                licenseIsRight = this->checkLicence(msg);
            } else {
                return licenseIsRight;
            }
        }
    }

    return licenseIsRight;

}



bool licence::getDeviceInfo(DEVICEIDLIST& devIDList)
{
    return get_mac(devIDList);
}

bool licence::idToLicence(QString &devID, LICENCE &licence)
{
    DES des;
    des.Des_Go(licence.licence, devID.toLatin1().data(), devID.length(), ENCRYPT);
     return true;
}

bool licence::licenceToId(char* license, char *devID)
{
    DES des;
    des.Des_Go(devID, license, strlen(license), DECRYPT);
     return true;
}


#define MAXINTERFACES   16
bool licence::get_mac(DEVICEIDLIST& macList)
{
#ifdef Q_OS_LINUX
    register int fd, intrface, retn = 0;
    struct ifreq buf[MAXINTERFACES];
    struct ifconf ifc;
    if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0)
    {
        ifc.ifc_len = sizeof(buf);
        ifc.ifc_buf = (caddr_t) buf;
        if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc))
        {
            //获取接口信息
            intrface = ifc.ifc_len / sizeof (struct ifreq);

//            printf("interface num is intrface=%d ",intrface);

            //根据接口信息循环获取设备MAC地址
            while (intrface-- > 0)
            {
                //获取设备名称
//                printf ("net device %s ", buf[intrface].ifr_name);

                if (!(ioctl (fd, SIOCGIFHWADDR, (char *) &buf[intrface])))
                {
                    char mac_addr[30] = {0};

                    sprintf(mac_addr, "%02x%02x%02x%02x%02x%02x",
                            (unsigned char)buf[intrface].ifr_hwaddr.sa_data[0],
                            (unsigned char)buf[intrface].ifr_hwaddr.sa_data[1],
                            (unsigned char)buf[intrface].ifr_hwaddr.sa_data[2],
                            (unsigned char)buf[intrface].ifr_hwaddr.sa_data[3],
                            (unsigned char)buf[intrface].ifr_hwaddr.sa_data[4],
                            (unsigned char)buf[intrface].ifr_hwaddr.sa_data[5]);

                    QString temp(mac_addr);
                    if(!temp.isEmpty())
                    {
                        macList.append(temp);

                        retn++;
                    }
                }
            } //while
        }
    }

    close (fd);
    return (retn>0);
#else
    return false;
#endif
}
